<?php
namespace app\job;

use app\common\logic\OrderLogic;
use app\common\model\Order;
use app\common\model\OrderAftersales;
use app\common\model\OrderAftersalesRecord;
use app\common\model\ShopMember;
use think\Db;
use think\Exception;
use think\Log;
use think\Queue;
use think\queue\Job;

class CancelOrder extends BaseJob
{
    /**
     * 超时未核销订单列取消
     * @param Job $job
     * @param $data
     */
    public function handle(Job $job, $data)
    {
        Db::startTrans();//开启事务
        try{
            // 有些消息在到达消费者时,可能已经不再需要执行了
            $order = Order::get(['id'=>$data['id'],'order_status'=>Order::ORDER_STATUS_WAIT_AUDIT]);
            if (!empty($order)){
                $order->order_status      = Order::ORDER_STATUS_REFUND;//退款/售后
                $order->refund_apply_time = time();
                $order->save();
                //查看之前是否有申请过
                $res = OrderAftersales::get(['order_id'=>$order['id'], 'shop_id'=>$order['shop_id'], 'member_id'=>$order['member_id']]);
                if (!empty($res)){
                    $res->status = OrderAftersales::STATUS_OK;
                    $res->reason = '过期自动退款';
                    $res->save();
                }else{
                    $res = OrderAftersales::create(['order_id'=>$order['id'], 'shop_id'=>$order['shop_id'], 'member_id'=>$order['member_id'], 'order_amount'=>$order['order_amount'],
                        'status'=>OrderAftersales::STATUS_OK,
                        'refund'=>$order['pay_amount'],
                        'pay_type'=>$order['pay_type'],
                        'transaction_id'=>$order['transaction_id'],
                        'agent_id'=>$order['agent_id'],
                        'reason'=>'过期自动退款',
                    ]);
                }
                $orderLogic = new OrderLogic();
                if ($orderLogic->refund($order['id'])){
                    OrderAftersalesRecord::create(['order_id'=>$order['id'],'order_aftersales_id'=>$res->id,'status'=>3]);
                }else{
                    throw new Exception("超时未核销订单ID：{$order['id']}，退款失败");
                }
            }
            Db::commit();
            $member_list = ShopMember::where(['shop_id'=>$order['shop_id'],'is_del'=>0])->select();
            if (!empty($member_list)){
                foreach ($member_list as $v){
                    Queue::push(Message::class,[
                        'member_id'=>$v['member_id'],
                        'template_id'=>config('wechat_gzh')['gzh_template']['cancel_order'],
                        'pagepath'=>'pages/shop/order/index',
                        'data'=>[
                            'character_string1'=>$order['order_sn'],
                            'time3'=>date('Y-m-d H:i')
                        ]
                    ],'message');
                }
            }
        }catch (Exception $e){
            Db::rollback();
            Log::error($e->getMessage());
            throw $e;
        }
    }









}